<template>
  <div class="app-container">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleImport"
            v-hasPermi="['order:order:add']">批量导入订单</el-button>
        </el-col>

        <el-col :span="1.5" class="right-align-col">
          <el-button type="danger" plain icon="Monitor" @click="handleSave"
            v-hasPermi="['order:order:remove']">保存分架</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="CircleCheck" @click="handleNext"
            v-hasPermi="['order:order:export']">确认分架</el-button>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form :model="queryOrderParams" ref="queryOrderRef" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="订单名称" prop="name">
                  <el-input v-model="queryOrderParams.name" placeholder="请输入订单名称"  @keyup.enter="handleOrderQuery"
                    style="width: 120px" />
                </el-form-item>

                <el-form-item label="厚度" prop="beginThickness">
                  <el-input v-model="queryOrderParams.beginThickness" placeholder="请输入厚度下限"  @keyup.enter="handleOrderQuery"
                    style="width: 120px" />
                </el-form-item>
                <el-form-item label="" prop="endThickness">
                  <el-input v-model="queryOrderParams.endThickness" placeholder="请输入厚度上限"  @keyup.enter="handleOrderQuery"
                    style="width: 120px" />
                </el-form-item>
              
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleOrderQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetOrderQuery">重置</el-button>
                </el-form-item>
              

              <el-table v-loading="loading" :data="orderList" 
              @sort-change="handleOrderSortChange" :row-class-name="tableRowClassName">
                <el-table-column label="订单名称" align="center" sortable="custom" prop="name" />
                <el-table-column label="总片数" align="center" sortable="custom" prop="piecesNumber" />
                <el-table-column label="总箱数" align="center" sortable="custom" prop="boxesNumber" />
                <el-table-column label="厚度" align="center" sortable="custom" prop="thickness" />
                <el-table-column label="最小面积" align="center" sortable="custom" prop="minArea" />
                <el-table-column label="最大面积" align="center" sortable="custom" prop="maxArea" />
                <el-table-column label="颜色" align="center" sortable="custom" prop="color" />
                <el-table-column label="操作" align="center" show-overflow-tooltip width="200px"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="primary" icon="select" @click="handleOrderUpdate(scope.row)"
                      v-hasPermi="['order:order:edit']">{{ selectedOrderIdList.indexOf(scope.row.id) !== -1 ? '取消' :
                        '选择' }}</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleOrderDelete(scope.row)"
                      v-hasPermi="['order:order:remove']">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
          

            
              <pagination v-show="orderTotal > 0" :total="orderTotal" v-model:page="queryOrderParams.pageNum"
                v-model:limit="queryOrderParams.pageSize" @pagination="getOrderList" />
          </el-form>
        </el-col>


        <el-col :span="1">
        </el-col>

        <el-col :span="11">
          <el-form :model="queryRequirementParams" ref="queryRequirementRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="架类型" prop="shelfId">
              <el-input v-model="queryRequirementParams.shelfId" placeholder="请输入架类型" clearable @keyup.enter="handleRequirementQuery"
                style="width: 120px" />
            </el-form-item>
            <el-form-item label="架号" prop="shelfNum">
              <el-input v-model="queryRequirementParams.shelfNum" placeholder="请输入架号" clearable @keyup.enter="handleRequirementQuery"
                style="width: 120px" />
            </el-form-item>
    
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleRequirementQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetRequirementQuery">重置</el-button>
            </el-form-item>


          <el-table v-loading="loading" :data="requirementList"
            :row-class-name="requirementRowClassName" height="700px">
            <el-table-column label="片数" align="center" prop="piecesNumber" />
            <el-table-column label="长度" align="center" prop="length" />
            <el-table-column label="宽度" align="center" prop="width" />
            <el-table-column label="架类型" align="center" prop="shelfId">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.shelfId" 
                  placeholder="请选择架类型"
                  @change="handleShelfTypeChange(scope.$index)">
                  <el-option
                    v-for="item in shelfList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="架号" align="center" prop="shelfNum">
              <template #default="scope">
                <el-input 
                  v-model.number="scope.row.shelfNum" 
                  placeholder="请输入架号" 
                  type="number"
                  @input="handleShelfNumberInput(scope.$index)" />
              </template> 
            </el-table-column>
            <el-table-column label="架内序" align="center" prop="shelfOrder">
              <template #default="scope">
                <el-input 
                  v-model.number="scope.row.shelfOrder" 
                  placeholder="请输入架内序" 
                  type="number"
                  @input="handleShelfIndexInput(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
            <!-- <pagination v-show="requirementTotal > 0" :total="requirementTotal" v-model:page="queryRequirementParams.pageNum"
              v-model:limit="queryRequirementParams.pageSize" @pagination="getRequirementList" /> -->
            </el-form>
        </el-col>

      </el-row>
    <!-- </div>
  </div> -->


    <!-- 批量导入对话框 -->

    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-form :model="upload" label-width="100px">
        <el-form-item label="厚度">
          <el-input v-model="upload.thickness" placeholder="请输入厚度" type="number" />
        </el-form-item>
      </el-form>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" 
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&thickness=' + upload.thickness"
        enctype="multipart/form-data" :headers="upload.headers"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-exceed="handleExceed"
        :on-change="handleChange" :fileList="fileList" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
        
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">

import { getToken } from "@/utils/auth";
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order";
import { listRequirementByOrderIds } from "@/api/order/requirement";
import { listShelf } from "@/api/order/shelf";
import { ElMessage } from "element-plus";
import useOrderStore from '@/store/modules/order'


const { proxy } = getCurrentInstance();
const orderStore = useOrderStore();

const orderList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const orderTotal = ref(0);
const requirementTotal = ref(0);
const fileList = ref([]);
const selectedOrderIdList = ref([]);
const selectedOrderThicknessList = ref([]);
const requirementList = ref([]);
const router = useRouter();
const shelfList = ref([]);
const hasChange = ref(false);


const orderData = reactive({
  orderForm: {},
  queryOrderParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    beginThickness: null,
    endThickness: null,
    status: 0,
  },
  orderRules: {
  }
});

const requirementData = reactive({
  requirementForm: {},
  queryRequirementParams: {
    pageNum: 1,
    pageSize: 10,
    shelfId: null,
    shelfNum: null,
    shelfIndex: null,
    orderIds: null,
  },
  requirementRules: {
  }
});

/*** 订单导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题（批量导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  thickness: '',
  url: import.meta.env.VITE_APP_BASE_API + "/order/order/importData"
});

const { queryOrderParams, orderForm, orderRules } = toRefs(orderData);
const { queryRequirementParams, requirementForm, requirementRules } = toRefs(requirementData);

const rowClassNames = ref([
  'danger9','primary9','warning9','success9','info9', 'danger8','primary8','warning8','success8','info8', 
  'danger7','primary7','warning7','success7','info7', 'danger5','primary5','warning5','success5','info5', 
  'danger3','primary3','warning3','success3','info3', 'danger2','primary2','warning2','success2','info2'
 
]);

const rowClassMap = ref({});

/** 查询订单选择列表 */
function getOrderList() {
  loading.value = true;
  listOrder(queryOrderParams.value).then(response => {
    orderList.value = response.rows;
    orderTotal.value = response.total;
    selectedOrderIdList.value = selectedOrderIdList.value.filter(id => orderList.value.some(order => order.id === id));
    selectedOrderThicknessList.value = selectedOrderThicknessList.value.filter(thickness => selectedOrderIdList.value.some(id => orderList.value.find(order => order.id === id && order.thickness === thickness)));
    loading.value = false;
    if (selectedOrderIdList.value.length > 0) {
    selectedOrderIdList.value.forEach((orderId, index) => {
      if (index < rowClassNames.value.length) {
        rowClassMap.value[orderId] = rowClassNames.value[index];
      }
    });
    getRequirementList();
  }
  });
}


// 表单重置
function orderReset() {
  orderForm.value = {
    id: null,
    createTime: null,
    createrId: null,
    name: null,
    piecesNumber: null,
    boxesNumber: null,
    thickness: null,
    minArea: null,
    maxArea: null,
    status: 0,
    operationId: null,
    beginThickness: null,
    endThickness: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleOrderQuery() {
  queryOrderParams.value.pageNum = 1;
  getOrderList();
}

/** 重置按钮操作 */
function resetOrderQuery() {
  proxy.resetForm("queryOrderRef"); 
  handleOrderQuery();
}





/** 选择按钮操作 */
function handleOrderUpdate(row) {
  if (row.id != null) {
    if (selectedOrderIdList.value.indexOf(row.id) === -1) {
      // 选中时分配样式
      selectedOrderIdList.value.push(row.id);
      const usedClasses = Object.values(rowClassMap.value);
      const availableClass = rowClassNames.value.find(className => 
        !usedClasses.includes(className)
      );
      if (availableClass) {
        rowClassMap.value[row.id] = availableClass;
      }
      selectedOrderThicknessList.value.push(row.thickness);

    } else {
      // 取消选中时移除样式
      selectedOrderIdList.value.splice(selectedOrderIdList.value.indexOf(row.id), 1);
      delete rowClassMap.value[row.id];
      selectedOrderThicknessList.value.splice(selectedOrderThicknessList.value.indexOf(row.thickness), 1);

    }
  }
  getRequirementList();
}



/** 删除按钮操作 */
function handleOrderDelete(row) {
  proxy.$modal.confirm('是否确认删除订单名称为"' + row.name + '"的数据项？').then(function () {
    return delOrder(row.id);
  }).then(() => {
    getOrderList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}



/**选择列的颜色 */
function tableRowClassName({ row }) {
  return rowClassMap.value[row.id] || '';
}

function requirementRowClassName({ row }) {
  return rowClassMap.value[row.orderId] || '';
}


function handleImport() {
  upload.title = "订单导入";
  upload.open = true;
}

/** 获取右侧列表 */
function getRequirementList() {
  if (hasChange.value && requirementList.value.length != 0) {
    handleSave(false);
  }
  loading.value = true;
  if (selectedOrderIdList.value.length > 0) {
    queryRequirementParams.value.orderIds = selectedOrderIdList.value;
    listRequirementByOrderIds(queryRequirementParams.value).then(response => {
      requirementList.value = response.rows;
      loading.value = false;
      requirementTotal.value = response.total;
    });
  } else {
    requirementList.value = [];
    requirementTotal.value = 0;
    loading.value = false;
  }
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("order/order/importTemplate", {
  }, `order_template_${new Date().getTime()}.xlsx`);
};


function handleExceed(files, fileList) {

  ElMessage.error(`最多只能选择一个文件`);
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getOrderList();
};

/** 文件上传改变处理 */
const handleChange = (file, fileList1) => {
  fileList.value = fileList1;
}

/** 下一步操作 */
function handleNext() {
  if (selectedOrderIdList.value.length == 0) {
    proxy.$modal.msgError("请选择至少一个订单");
    return;
  }

  const uniqueThicknessList = [...new Set(selectedOrderThicknessList.value)];
  if (uniqueThicknessList.length > 1) {
    proxy.$modal.msgError("只能选择一种厚度的订单");
    return;
  }


  orderStore.setOrdersIds(selectedOrderIdList.value);
  orderStore.setOrdersThicknessList(selectedOrderThicknessList.value);
  router.push("/order/original");
}

/** 提��上传文件 */
function submitFileForm(event) {
  proxy.$refs["uploadRef"].submit()
};

function handleOrderSortChange(column) {
  queryOrderParams.value.orderByColumn = column.prop;
  if(column.order == 'ascending') {
    queryOrderParams.value.isAsc = 'ASC';
  } else if(column.order == 'descending') {
    queryOrderParams.value.isAsc = 'DESC';
  } else {
    queryOrderParams.value.isAsc = null;
    queryOrderParams.value.orderByColumn = null;
  }
  getOrderList();
}

function handleRequirementQuery() {
  queryRequirementParams.value.pageNum = 1;
  getRequirementList();

}

function resetRequirementQuery() {
  proxy.resetForm("queryRequirementRef"); 
  handleRequirementQuery();
}

function getShelfList() {
  listShelf().then(response => {
    shelfList.value = response.rows;
  });
}

function handleSave(showMsg = true) {
  updateRequirementBatch(requirementList.value).then(response => {
    if(showMsg) {
      proxy.$modal.msgSuccess("保存成功");
    }
    hasChange.value = false;
  });
}

function handleShelfNumberInput(currentIndex) {
  // 获取当前行的值
  const currentValue = requirementList.value[currentIndex].shelfNum;
  
  // 如果输入有效，则自动填充后续行
  if (currentValue !== null && currentValue !== undefined) {
    // 从下一行开始填充相同的值
    for (let i = currentIndex + 1; i < requirementList.value.length; i++) {
      requirementList.value[i].shelfNum = currentValue;
    }
  }
  hasChange.value = true;
}

function handleShelfIndexInput(currentIndex) {
  // 获取当前行的值
  const currentValue = requirementList.value[currentIndex].shelfOrder;
  
  // 如果输入有效，则自动填充后续行，递增填充
  if (currentValue !== null && currentValue !== undefined) {
    // 从下一行开始填充递增值
    for (let i = currentIndex + 1; i < requirementList.value.length; i++) {
      requirementList.value[i].shelfOrder = currentValue + (i - currentIndex);
    }
  }
  hasChange.value = true;
}

function handleShelfTypeChange(currentIndex) {
  // 获取当前行的架类型值
  const currentValue = requirementList.value[currentIndex].shelfId;
  
  // 如果选择了有效值，则自动填充后续行
  if (currentValue) {
    // 从下一行开始填充相同的架类型
    for (let i = currentIndex + 1; i < requirementList.value.length; i++) {
      requirementList.value[i].shelfId = currentValue;
    }
  }
  hasChange.value = true;
}

onActivated(() => {
  
  selectedOrderIdList.value = orderStore.ordersIds;
  selectedOrderThicknessList.value = orderStore.ordersThicknessList;
  getOrderList();
  getShelfList();
})
</script>
<style>
.table-container {
  display: flex;
  justify-content: space-between;
}

.table-item {
  flex: 1;
  margin: 0 10px;
}

.right-align-col {
  margin-left: auto;
}

.el-table .warning9 {
  --el-table-tr-bg-color: var(--el-color-warning-light-9) !important;
}
.el-table .warning8 {
  --el-table-tr-bg-color: var(--el-color-warning-light-8) !important;
}
.el-table .warning7 {
  --el-table-tr-bg-color: var(--el-color-warning-light-7) !important;
}
.el-table .warning5 {
  --el-table-tr-bg-color: var(--el-color-warning-light-5) !important;
}
.el-table .warning3 {
  --el-table-tr-bg-color: var(--el-color-warning-light-3) !important;
}
.el-table .warning2 {
  --el-table-tr-bg-color: var(--el-color-warning-dark-2) !important;
}
.el-table .success9 {
  --el-table-tr-bg-color: var(--el-color-success-light-9) !important;
}
.el-table .success8 {
  --el-table-tr-bg-color: var(--el-color-success-light-8) !important;
}
.el-table .success7 {
  --el-table-tr-bg-color: var(--el-color-warning-light-7) !important;
}
.el-table .success5 {
  --el-table-tr-bg-color: var(--el-color-success-light-5) !important;
}
.el-table .success3 {
  --el-table-tr-bg-color: var(--el-color-success-light-3) !important;
}
.el-table .success2 {
  --el-table-tr-bg-color: var(--el-color-success-dark-2) !important;
}

.el-table .primary9 {
  --el-table-tr-bg-color: var(--el-color-primary-light-9) !important;
}
.el-table .primary8 {
  --el-table-tr-bg-color: var(--el-color-primary-light-8) !important;
}
.el-table .primary7 {
  --el-table-tr-bg-color: var(--el-color-primary-light-7) !important;
}
.el-table .primary5 {
  --el-table-tr-bg-color: var(--el-color-primary-light-5) !important;
}
.el-table .primary3 {
  --el-table-tr-bg-color: var(--el-color-primary-light-3) !important;
}
.el-table .primary2 {
  --el-table-tr-bg-color: var(--el-color-primary-dark-2) !important;
}

.el-table .danger9 {
  --el-table-tr-bg-color: var(--el-color-danger-light-9) !important;
}
.el-table .danger8 {
  --el-table-tr-bg-color: var(--el-color-danger-light-8) !important;
}
.el-table .danger7 {
  --el-table-tr-bg-color: var(--el-color-danger-light-7) !important;
}
.el-table .danger5 {
  --el-table-tr-bg-color: var(--el-color-danger-light-5) !important;
}
.el-table .danger3 {
  --el-table-tr-bg-color: var(--el-color-danger-light-3) !important;
}
.el-table .danger2 {
  --el-table-tr-bg-color: var(--el-color-danger-dark-2) !important;
}

.el-table .info9 {
  --el-table-tr-bg-color: var(--el-color-info-light-9) !important;
}
.el-table .info8 {
  --el-table-tr-bg-color: var(--el-color-info-light-8) !important;
}
.el-table .info7 {
  --el-table-tr-bg-color: var(--el-color-info-light-7) !important;
}
.el-table .info5 {
  --el-table-tr-bg-color: var(--el-color-info-light-5) !important;
}
.el-table .info3 {
  --el-table-tr-bg-color: var(--el-color-info-light-3) !important;
}
.el-table .info2 {
  --el-table-tr-bg-color: var(--el-color-info-dark-2) !important;
}
</style>